package cn.antho.pet.service.impl;

import cn.antho.org.domain.Department;
import cn.antho.pet.domain.PetType;
import cn.antho.pet.mapper.PetTypeMapper;
import cn.antho.pet.service.IPetTypeService;
import cn.antho.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author antho
 * @since 2022-10-28
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTypeTree() {
        List<PetType> allPetTypes = petTypeMapper.findAll();
        // stream流
        Map<Long, PetType> parentMap = allPetTypes.stream().collect(Collectors.toMap(PetType::getId, e -> e));
        // 同理
        List<PetType> result = new ArrayList<>();
        // 遍历
        for (PetType petType : allPetTypes) {
            if (null == petType.getPid()) {
                // 如果没有上级id，则自己就是老大
                result.add(petType);
            } else {
                // 有上级id，找爹
                PetType parent = parentMap.get(petType.getPid());
                if (null == parent) {
                    break ;
                }
                List<PetType> children = parent.getChildren();
                children.add(petType);
            }
        }
        return result;
    }
}
